package cn.smbms.web.controller.user;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.service.user.UserServiceImpl;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;

@Controller("userController")
@RequestMapping("/user")
public class UserController {
	Logger log = Logger.getLogger(UserController.class);
	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;
	/**
	 * 进入登录界面
	 * @return
	 */
	@RequestMapping(value="/login.do",method=RequestMethod.GET)
	public String login(){
	//	log.info("login() get=====================");
		return "login";
	}
	/**
	 * 执行登录操作
	 * @param userCode
	 * @param userPassword
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/login.do",method=RequestMethod.POST)
	public String login(@RequestParam String userCode,
			@RequestParam("userPassword") String userPassword,HttpServletRequest request){
		//log.info("login() post=====================");
		User user = userService.login(userCode, userPassword);
		if (user != null) {//登录成功
			//放入session
			request.getSession().setAttribute(Constants.USER_SESSION, user);
			//页面跳转（frame.jsp）
			return "redirect:/user/main.html";
		} else {
			//页面跳转（login.jsp）带出提示信息--转发
			request.setAttribute("error", "用户名或密码不正确");
			return "login";
		}
	}
	/*
	 * 跳转到主页面
	 */
	@RequestMapping(value="/main.html",method=RequestMethod.GET)
	public String main(HttpSession session){
	//	log.info("main get=====================");
		User user = (User) session.getAttribute(Constants.USER_SESSION);
		if (user == null) {
			return "redirect:/error.jsp";
		}
		return "frame";
	}
	// 注意：method的属性默认值是get和post
	@RequestMapping(value="/userlist.html",method={RequestMethod.GET,RequestMethod.POST})
	public String userlist(Model model,
						@RequestParam(value="queryname",required=false) String queryUserName,
						@RequestParam(value="queryUserRole",required=false) String queryUserRole,
						@RequestParam(value="pageIndex",required=false) String pageIndex){
		//查询用户列表
    	//设置用户名
		if(queryUserName == null){
			queryUserName = "";
		}
		//设置用户角色
		int _queryUserRole = 0;
		if(queryUserRole != null && !queryUserRole.equals("")){
			_queryUserRole = Integer.parseInt(queryUserRole);
		}
		//设置页面容量
    	int pageSize = Constants.pageSize;
		//当前页码
    	int currentPageNo = 1;
    	if(pageIndex != null){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
    			return "redirect:/user/error.html";
    		}
    	}	
    	//总数量（表）	
    	int totalCount	= userService.getUserCount(queryUserName,_queryUserRole);
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	// 总页数
    	int totalPageCount = pages.getTotalPageCount();
    	
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
		
		
    	List<User> userList = userService.getUserList(queryUserName,_queryUserRole,(currentPageNo-1)*pageSize, pageSize);
		model.addAttribute("userList", userList);
		List<Role> roleList = null;
		roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		return "/userlist";
	}
	/*
	 * 进入添加用户页面
	 */
	@RequestMapping(value="/useradd.html", method=RequestMethod.GET)
	public String addUser(){
		
		return "/useradd";
	}
	/*
	 * 添加用户信息
	 */
	@RequestMapping(value="/useradd.html", method=RequestMethod.POST)
	public String addUser(@Validated @ModelAttribute User user, BindingResult bindingResult, Model model,HttpSession session){
		// 服务器端验证
		if (bindingResult.hasErrors()) {
			List<FieldError> errors = bindingResult.getFieldErrors();
			for (FieldError error : errors) {
				model.addAttribute(error.getField(), error.getDefaultMessage());
			}
			return "/useradd";
		}
		
		user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		if (userService.add(user)) {
			return "redirect:/user/userlist.html";
		} else {
			return "/useradd";
		}
	}
	/*
	 * 获取所有角色信息
	 */
	@RequestMapping(value="/getrolelist.html",method=RequestMethod.GET)
	@ResponseBody
	public List<Role> getrolelist(){
		return roleService.getRoleList();
	}
	/*
	 * 判断用户编号是否已经存在
	 */
	@RequestMapping(value="/ucexist.html",method=RequestMethod.GET)
	@ResponseBody
	public String userCodeExist(@RequestParam String userCode){
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if(StringUtils.isNullOrEmpty(userCode)){
			resultMap.put("userCode", "exist");
		}else{
			User user = userService.selectUserCodeExist(userCode);
			if (user != null) {
				resultMap.put("userCode", "exist");
			}else{
				resultMap.put("userCode", "notexist");
			}
		}
		
		return JSON.toJSONString(resultMap);
	}
	/*
	 * 进入更新页面
	 */
	@RequestMapping(value="/modifyUser.html", method=RequestMethod.GET)
	public String modifyUser(@RequestParam("uid") String id, Model model){
		User user = userService.getUserById(id);
		model.addAttribute("user", user);
		return "/usermodify";
	}
	/*
	 * 更新用户信息
	 */
	@RequestMapping(value="/usermodify.html", method=RequestMethod.POST)
	public String modifyUser(User user,HttpServletRequest request){
		User user1 = userService.getUserById(user.getId().toString());
		user1.setUserName(user.getUserName());
		user1.setGender(user.getGender());
		user1.setBirthday(user.getBirthday());
		user1.setPhone(user.getPhone());
		user1.setAddress(user.getAddress());
		user1.setUserRole(user.getUserRole());
		user1.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
		user1.setModifyDate(new Date());
		if (userService.modify(user1)) {
			return "redirect:/user/userlist.html";
		} else {
			return "/usermodify";
		}
	}
	/*
	 * 删除
	 * **/
	@RequestMapping("/deleteUser")
	@ResponseBody
	public String deleteUser(@RequestParam("uid") int uid){
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if(uid <= 0){
			resultMap.put("delResult", "notexist");
		}else{
			
			if(userService.deleteUserById(uid)){
				resultMap.put("delResult", "true");
			}else{
				resultMap.put("delResult", "false");
			}
		}
		return JSONArray.toJSONString(resultMap);
		
		
	}
	//注册一个属性编辑器
	@InitBinder
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder){
		//将student类中的birthday属性进行日期转换，类型和birthday一致
		binder.registerCustomEditor(Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
}
